<!-- 1 脚本 -->
<script lang="ts" setup name="TabContent">
import { type TabPaneName } from 'element-plus'
import type { LayoutRoute } from '@/types'
import { useLayoutRouterStore } from '@/stores/useLayoutRouterStore'
import { storeToRefs } from 'pinia'

//路由表整个大对象
const router = useRouter()

//当前的路由信息
const route = useRoute()

//选项卡存储在  pinia中
const layoutRouterStore = useLayoutRouterStore()

const activeName = ref('/welcome')

// { label: '首页', name: '/welcome', path: "/welcome", closable: false },
const { menuContents } = storeToRefs(layoutRouterStore)

/***
 * 切换 选项卡的时候触发路由跳转
 */
function changMenuTab(name: TabPaneName) {
  router.push(name as string)
}

/**
 * 删除选项卡
 */
function removeMenuTab(path: string) {
  //删除 选项卡 返回 最后一个菜单项
  const lastMenuContent = layoutRouterStore.removeMenuContent(path as string)
  // 激活最后一个
  activeName.value = lastMenuContent.path

  //切换路由
  router.push(lastMenuContent.path)
}

/**
 *
 * 判断当前选项卡是否存在该路径
 * @param path
 */

function existxMenuContent(path: string) {
  let flag = false
  menuContents.value.forEach((item) => {
    if (item.path === path) {
      flag = true
    }
  })

  return flag
}

//监听 route的变化
watch(
  route,
  (newRoute) => {
    const { path: newPath } = newRoute
    if (!existxMenuContent(newPath)) {
      const newLayoutRoute: LayoutRoute = {
        path: newRoute.path,
        meta: newRoute.meta,
      }
      menuContents.value.push(newLayoutRoute)
    }

    activeName.value = newPath
  },
  {
    immediate: true, //让进入页面 时候立即执行一次，否则 可能刷新之后 没有添加选项卡
  },
)
</script>

<!-- 2 模板 -->
<template>
  <div class="container">
    <div class="menuTabWrapper">
      <el-tabs v-model="activeName" @tab-change="changMenuTab" @tab-remove="removeMenuTab" class="menuTab">
        <el-tab-pane v-for="menuContent in menuContents" :name="menuContent.path"
          :closable="menuContent.path !== '/welcome'" :key="menuContent.path">
          <template #label>
            <template v-if="menuContent.meta?.icon">
              <el-icon>
                <component :is="menuContent.meta ? menuContent.meta.icon : ''"></component>
              </el-icon> </template><span>{{ menuContent.meta ? menuContent.meta.title : '' }}</span>
          </template>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- http://localhost/system/user -->
    <!-- http://localhost/system/todo -->
    <RouterView></RouterView>
  </div>
</template>

<!-- 3 样式 -->
<style scoped>
.container {
  padding-left: 2px;
}

/* box-shadow: 0px 0px 50px #929192; */
.container .menuTabWrapper {
  margin-bottom: 0px;
}
</style>
